package com.fubowen.reader.extension

import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import java.net.URL

private val regex = Regex("^[^\\p{IsAlphabetic}\\d\\p{IsHan}]+|[(（][^)）]*[)）]|[^\\p{IsAlphabetic}\\d\\p{IsHan}]+$")

fun String?.trimChar() = this?.let { regex.replace(it, "") }
fun String?.getDocument(tryCount: Int = 3, timeout: Int = 30000, userAgent: String = AGENT, callback: (Boolean, Document?, String?) -> Unit) {
    this?.let {
        var document: Document? = null
        var state = false
        var msg: String? = null
        for (i in 0 until tryCount) {
            try {
                document = Jsoup.connect(it)
                    .timeout(timeout)
                    .userAgent(userAgent)
                    .get()
                state = true
                break
            } catch (e: Exception) {
                msg = e.message
            }
        }
        callback(state, document, msg)
    }
}

fun String.isUrlToGetBaseUrl(): String {
    val url = URL(this)
    val protocol = url.protocol
    val host = url.host
    val port = if (url.port != -1) ":" + url.port else ""
    return "$protocol://$host$port"
}

fun String.isRegex(): Boolean {
    return try {
        Regex(this)
        true
    } catch (e: Exception) {
        false
    }
}

fun String.toNumber(): Int {
    val num = this.toIntOrNull()
    if (num != null) {
        return num
    }
    var unit = mutableListOf<String>()
    var index = 0
    var hasUnit = false

    var number = 0
    val numEnum = listOf("零", "一", "二", "三", "四", "五", "六", "七", "八", "九")
    val unitEnum = listOf("十", "百", "千", "万")
    for (ch in this.reversed()) {

        val numIndex = numEnum.indexOf(ch.toString())
        if (numIndex != -1) {
            if (hasUnit) {
                unit[index] = numIndex.toString()
                index++
            } else {
                unit.add(0, numIndex.toString())
            }
        }
        val unitIndex = unitEnum.indexOf(ch.toString())
        if (unitIndex != -1) {
            if (unit.isNotEmpty()) {
                val dd = unit.joinToString("")
                number += dd.toInt()
            }
            index = 0
            unit = (mutableListOf("1") + MutableList(unitIndex + 1) { "0" }).toMutableList()
            hasUnit = true
        }
    }
    if (unit.isNotEmpty()) {
        number += unit.joinToString("").toInt()
    }
    return number
}

inline fun <reified T> String?.toTarget(): T? {
    val value = when (T::class.java) {
        T::class.java -> this?.toIntOrNull()
        Double::class.java -> this?.toDoubleOrNull()
        String::class.java -> this
        Float::class.java -> this?.toFloatOrNull()
        Boolean::class.java -> this.toBoolean()
        Long::class.java -> this?.toLongOrNull()
        else -> throw java.lang.ClassCastException("不能识别的类型${T::class.java}")
    }
    return value as T?
}